
// 账号的验证
var loginIdValidator = new FieldValidator('txtLoginId',async function(val) {
    if(!val) {
        return '请填写账号';
    }
    const resp = await API.exists(val);
    if(resp.data) {
        // 账号已经存在
        return '该账号已被占用'
    }
})
console.log(loginIdValidator);

// 昵称的验证
var nicknameValidator = new FieldValidator('txtNickname',async function(val) {
    if(!val) {
        return '请填写昵称';
    }
});

// 密码的验证
var loginPwdValidator = new FieldValidator('txtLoginPwd',async function(val) {
    if(!val) {
        return '请填写密码';
    }
});

// 密码的再次验证
var txtLoginPwdConfirmValidator = new FieldValidator('txtLoginPwdConfirm',async function(val) {
    if(!val) {
        return '请填写确认密码';
    }
    if(val !== loginPwdValidator.input.value) {
        return '两次密码不一致';
    }
});

const form = $('.user-form');
form.onsubmit =async function(e) {
    e.preventDefault();
    const result = await FieldValidator.validate(loginIdValidator,nicknameValidator,loginPwdValidator,txtLoginPwdConfirmValidator);
    // console.log(result);
    if(!result) {
        return;  //验证未通过
    }
    // const data = {
    //     loginId: loginIdValidator.input.value,
    //     loginPwd: nicknameValidator.input.value,
    //     nickname: loginPwdValidator.input.value,
    // }
    // console.log(data);

    // formData.entries()  {a:1,b:2}=>[['a',1],['b',2]]
    // Object.fromEntries()  [['a',1],['b',2]]=>{a:1,b:2}
    // 验证通过，调用api注册
    const formData = new FormData(form);  //传入表单dom，获取表单数据对象
    const data = Object.fromEntries(formData.entries())
    console.log(data);
    const resp = await API.reg(data);
    console.log(resp);
    
    if(resp.code === 0) {
        alert('注册成功，点击确定跳转到登录页')
        location.href = './login.html';
    }
    
}